<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Exceptions\ApiException;
use App\Format\FlowFormat;
use App\Models\Flow;

class FlowService
{
    public function setFlow(FlowFormat $flowFormat)
    {
        if (empty($flowFormat->getId())) {
            return $this->createFlow($flowFormat);
        }
        return $this->updateFlow($flowFormat);
    }

    public function createFlow(FlowFormat $flowFormat)
    {
        if (Flow::query()->where('type', $flowFormat->getType())->exists()) {
            throw new ApiException('此类型流程图已经存在', 1);
        }
        Flow::query()->create($flowFormat->toArrayNotNull());
        return true;
    }

    public function updateFlow(FlowFormat $flowFormat)
    {
        $id = $flowFormat->getId();

        $flow = Flow::query()->find($id);
        if (empty($flow)) {
            throw new ApiException('数据不存在', 1);
        }

        $flowFormat->setId(null);

        $flow->update($flowFormat->toArrayNotNull());
        return true;
    }

    public function deleteFlow(int $id)
    {
        $flow = Flow::query()->find($id);
        if (empty($flow)) {
            throw new ApiException('数据不存在', 1);
        }
        $flow->delete();

        return true;
    }

    public function getFlowFromType(int $type)
    {
        $flow = Flow::query()->where('type', $type)->first();

        if (empty($flow)) {
            return new \stdClass();
        }

        return $flow;
    }

    public function getLists()
    {
        return Flow::query()->get();
    }
}
